package org.dahuatech.ssh.common.aop;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.dahuatech.ssh.common.utils.ConstantsUtils;
import org.dahuatech.ssh.entity.account.User;
import org.springframework.dao.DataAccessException;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

@SuppressWarnings("serial")
public class Interceptor extends AbstractInterceptor {

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		// TODO Auto-generated method stub
		before(invocation);
		String result = null;
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		Map<String,Object> sessionMap = ActionContext.getContext().getSession();
		User user = (User)sessionMap.get(ConstantsUtils.USER);
		if (user==null) {
			result = "timeout";
		} else {
			try {
				result = invocation.invoke();
			} catch (DataAccessException ex) {
				throw new Exception("数据库操作失败！", ex);
			} catch (NullPointerException ex) {
				throw new Exception("调用了未经初始化的对象或者是不存在的对象！", ex);
			} catch (IOException ex) {
				throw new Exception("IO异常！", ex);
			} catch (ClassNotFoundException ex) {
				throw new Exception("指定的类不存在！", ex);
			} catch (ArithmeticException ex) {
				throw new Exception("数学运算异常！", ex);
			} catch (ArrayIndexOutOfBoundsException ex) {
				throw new Exception("数组下标越界!", ex);
			} catch (IllegalArgumentException ex) {
				throw new Exception("方法的参数错误！", ex);
			} catch (ClassCastException ex) {
				throw new Exception("类型强制转换错误！", ex);
			} catch (SecurityException ex) {
				throw new Exception("违背安全原则异常！", ex);
			} catch (SQLException ex) {
				throw new Exception("操作数据库异常！", ex);
			} catch (NoSuchMethodError ex) {
				throw new Exception("方法末找到异常！", ex);
			} catch (InternalError ex) {
				throw new Exception("Java虚拟机发生了内部错误", ex);
			} catch (Exception ex) {
				throw new Exception("程序内部错误，操作失败！", ex);
			}
		}
		after(invocation, result);
		return result;
	}
	
	public  void before(ActionInvocation invocation) throws Exception{};

	public  void after(ActionInvocation invocation, String resultCode)throws Exception{};

}
